package uk.org.landeg.euler.problems;

import uk.org.landeg.euler.problems.framework.AbstractProblem;
import uk.org.landeg.euler.problems.framework.ProblemLauncher;
import uk.org.landeg.euler.problems.lib.NumbersLib;

public class Problem034 extends AbstractProblem{
	public static void main(String[] args) {
		ProblemLauncher launcher = new ProblemLauncher(new Problem034());
		launcher.solve();		
	}

	@Override
	public String getDescription() {
		return "Find the sum of all numbers which are equal to the sum of the factorial of their digits";
	}

	@Override
	public Integer getProblemNumber() {
		return 34;
	}

	int factorials[];
	private void makeFactorials () {
		factorials = new int[10];
		for (int idx =0  ;idx < 10 ; idx++) {
			if (idx == 0) {
				factorials[0] = 1;
			} else if (idx == 1) {
				factorials[1] = 1;
			} else {
				factorials[idx] = factorials[idx -1] * idx;
			}
		}
	}
	
	@Override
	public Object solve() {
		notes.add("Creating factorials");
		makeFactorials();
		StringBuilder b = new StringBuilder();
		for (int i = 0 ; i < factorials.length ; i++) {
			b.append(factorials[i] + ",");
		}
		notes.add(b.toString());
		notes.add("Brute force for all numbers < 1E6");
		int digits[];
		long sumOfFactorials;
		long sum = 0L;
		for (long n = 3; n< 1000000 ; n++) {
			sumOfFactorials = 0;
			digits = NumbersLib.getDigits(n);
			for (int d : digits) {
				sumOfFactorials += factorials[d];
			}
			if (sumOfFactorials == n) {
				System.out.println(n);
				sum += n;
			}
		}
		return sum;
	}

}
